package com.rock.code.common.util;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

/**
 * Created by zhongqing.han Cotter on 2019/4/25.
 */
public class Img2Str {
    /**
     *
     * @param jpgFile
     * @return 识别验证码图片，返回String
     * @throws Exception
     */
    public String getCode(String jpgFile) throws Exception {
        String code = "";
        File imgFile = new File(jpgFile);
        removeBackgroud(imgFile);
        ITesseract instance = new Tesseract();
        String path = imgFile.getParent();
        System.out.println(path);
        instance.setDatapath(path+"/tessdata");
        instance.setLanguage("eng");
        try {
            code = instance.doOCR(imgFile).trim();
        } catch (TesseractException e) {
            e.printStackTrace();
        }
        return code;
    }
    public static int isWhite(int colorInt) {
        Color color = new Color(colorInt);
        if (color.getRed() + color.getGreen() + color.getBlue() > 100) {
            return 1;
        }
        return 0;
    }
    // 验证码二值化
    public void removeBackgroud(File imgFile){
        if(imgFile.exists()){
            BufferedImage img = null;
            try {
                img = ImageIO.read(imgFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            int width = img.getWidth();
            int height = img.getHeight();
            for (int x = 0; x < width; ++x) {
                for (int y = 0; y < height; ++y) {
                    if (isWhite(img.getRGB(x, y)) == 1) {
                        img.setRGB(x, y, Color.WHITE.getRGB());
                    } else {
                        img.setRGB(x, y, Color.BLACK.getRGB());
                    }
                }
            }
            try {
                ImageIO.write(img, "jpg", imgFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }


}
